package com.dingreading.cloud.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.admin.dto.RealUsableNumDto;
import com.dingreading.cloud.admin.entity.*;
import com.dingreading.cloud.admin.service.*;
import com.dingreading.cloud.admin.util.bean.GoodsWetAvgUtil;
import com.dingreading.cloud.admin.util.bean.OrderFormV3Util;
import com.dingreading.cloud.admin.util.bean.PurchaseUtil;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/whPurchase")
@Api(tags = "总部-仓库采购管理")
public class WhPurchaseController {

    @Resource
    protected WhPurchaseService whPurchaseService;
    @Resource
    protected WhPurchaseGoodsService whPurchaseGoodsService;
    @Resource
    protected GoodsSuppliersService goodsSuppliersService;
    @Resource
    protected WhStockInService whStockInService;
    @Resource
    protected GoodsTypeService goodsTypeService;
    @Resource
    protected GoodsWetPriceService goodsWetPriceService;
    @Resource
    protected GoodsService goodsService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList", produces = "application/json; charset=UTF-8")
    public R<Object> pageList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购单号") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "状态 0.取消 1.完成 2.保存 3.待入库 4.入库中") @RequestParam(value = "status", required = false) Integer status
    ) {
        PageDto<WhPurchase> data = whPurchaseService.pageListRealNum(pageUtil, keyword, status);

        JSONArray array = new JSONArray();
        if (data.getList() != null) {
            List<WhPurchase> list = data.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                List<String> codes = list.stream().map(WhPurchase::getCode).collect(Collectors.toList());

                // 获取采购的实际入库数、剩余总库存数
                Map<String, RealUsableNumDto> numDtoMap = whStockInService.getRealNumAndUsableNumByPurchaseCode(codes);

                // 获取采购订单的商品列表
                List<WhPurchaseGoods> goodsList = whPurchaseGoodsService.getByCodes(codes);
                Map<String, List<WhPurchaseGoods>> goodsMap = new HashMap<>();
                if (CollectionUtils.isNotEmpty(goodsList)) {
                    goodsMap = goodsList.stream().collect(Collectors.groupingBy(WhPurchaseGoods::getPurchaseCode));
                }
                for (WhPurchase purchase : list) {
                    JSONObject jsonObject = JsonUtil.toJsonObject(purchase);
                    jsonObject.put("goodsList", goodsMap.get(purchase.getCode()));

                    RealUsableNumDto numDto = numDtoMap.get(purchase.getCode());
                    String realNum = "0";
                    String usableNum = "0";
                    if (numDto != null) {
                        realNum = numDto.getRealNum();
                        usableNum = numDto.getUsableNum();
                    }
                    jsonObject.put("realNum", realNum);
                    jsonObject.put("usableNum", usableNum);
                    array.add(jsonObject);
                }
            }
        }
        data.setList(array);
        return R.ok(data);
    }


    @ApiOperation(value = "采购时获取供应商的商品规格列表")
    @PostMapping(value = "/getGoodsTypes", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsTypes(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "商品名/商品规格名") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "商品种类id") @RequestParam(value = "categoryId", required = false) Long categoryId,
            @ApiParam(value = "供应商id") @RequestParam(value = "supplierId", required = false) Long supplierId,
            @ApiParam(value = "状态 1.启用 0.禁用") @RequestParam(value = "enabled", required = false) Integer enabled
    ) {
        Page<WhPurchaseGoods> pageList = goodsSuppliersService.purchaseGoodsList(pageUtil, name, supplierId, categoryId, enabled);

        PageBeanDto data = new PageBeanDto();
        data.setTotal(pageList.getTotalRow());
        data.setList(pageList.getRecords());
        return R.ok(data);
    }


    @ApiOperation(value = "获取详情")
    @PostMapping(value = "/get", produces = "application/json; charset=UTF-8")
    public R<Object> get(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购订单号") @RequestParam(value = "code") String code
    ) {
        WhPurchase data = whPurchaseService.getByCode(code);
        if (data == null) return R.fail("采购订单获取失败");

        List<WhPurchaseGoods> list = whPurchaseGoodsService.getByCode(code);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("purchase", data);
        jsonObject.put("goodsList", list);
        jsonObject.put("expressList", OrderFormV3Util.getExpress(data.getExpressInfo()));
        return R.ok(jsonObject);
    }


    @ApiOperation(value = "删除")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购订单号") @RequestParam(value = "code") String code
    ) {
        long cnt = whStockInService.getPurchaseCodeCnt(code, null);
        if (cnt > 0) return R.fail("已有入库记录不能删除");

        long l = whPurchaseService.dropData(code);
        if (l <= 0) return R.fail("删除失败");

        whPurchaseGoodsService.dropData(code);
        return R.ok();
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "新增采购订单")
    @PostMapping(value = "/newBean")
    public R<Object> newBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购订单号") @RequestParam(value = "code", required = false) String code,
            @ApiParam(value = "供应商id") @RequestParam(value = "supplierId", required = false) Long supplierId,
            @ApiParam(value = "供应商名称") @RequestParam(value = "supplierName", required = false) String supplierName,
            @ApiParam(value = "状态 2.保存 3.提交待入库") @RequestParam(value = "status", required = false) int status,
            @ApiParam(value = "采购的商品信息") @RequestBody(required = false) List<WhPurchaseGoods> goodsJson,
            @ApiParam(value = "快递信息:[{code:'',name:''}]") @RequestParam(value = "expressJson", required = false) String expressJson,
            @ApiParam(value = "快递金额") @RequestParam(value = "expressPrice", required = false) Double expressPrice,
            @ApiParam(value = "采购备注") @RequestParam(value = "remark", required = false) String remark
    ) {
        if (CollectionUtils.isEmpty(goodsJson))
            return R.fail("请选择要采购的商品");

        String expressInfo = null;
        if (StringUtils.isNotBlank(expressJson)) {
            JSONArray array = JSONArray.parseArray(expressJson);
            if (CollectionUtils.isEmpty(array)) {
                return R.fail("请填写快递信息");
            } else {
                expressInfo = OrderFormV3Util.newExpress(array);
                if (StringUtils.isBlank(expressInfo))
                    return R.fail("快递信息不完整");
            }
        }

        // 同一个供应商的商品不能重复采购
        Map<Long, Long> map = new HashMap<>();
        Set<Integer> realStatusList = new HashSet<>();
        for (WhPurchaseGoods goods : goodsJson) {
            boolean b = map.containsKey(goods.getGoodsTypeId());
            if (b) {
                Long value = map.get(goods.getGoodsTypeId());
                if (value.equals(goods.getSupplierId())) {
                    return R.fail("相同供应商的商品不能重复采购商品名：" + goods.getGoodsName() + "-" + goods.getGoodsTypeName());
                }
            } else {
                map.put(goods.getGoodsTypeId(), goods.getSupplierId());
            }
            realStatusList.add(goods.getRealStatus());
        }

        if (realStatusList.size() >= 2)
            return R.fail("实体商品和非实体商品不能同时采购");

        WhPurchase data = null;
        int numCnt = 0;
        double priceCnt = 0d;
        String purchaseCode = null;
        Date time = DateUtil.getNowDatetime();

        if (StringUtils.isBlank(code)) {
            // 新增
            purchaseCode = KitUtil.getPurchaseCode();
            String statusName = EnumType.Purchase.getStatus(status);
            for (WhPurchaseGoods goods : goodsJson) {
                goods.setPurchaseCode(purchaseCode);
                goods.setCreator(headStaffName);
                goods.setCreatorUid(headStaffUid);
                goods.setStatus(status);
                goods.setStatusName(statusName);
                // 总数量
                numCnt += NepUtil.nullToZero(goods.getBuyNum());
                // 总金额
                priceCnt = DoubleUtil.sum(priceCnt, NepUtil.nullToZero(goods.getPrice()));
            }
            whPurchaseGoodsService.saveOrUpdateBatch(goodsJson);

            data = new WhPurchase();
            data.setCode(purchaseCode);
            data.setProjectType(EnumType.BalanceProject.PURCHASE.getType());
            data.setProjectName(EnumType.BalanceProject.PURCHASE.getName());
            data.setSupplierId(supplierId);
            data.setSupplierName(supplierName);
            data.setCreator(headStaffName);
            data.setCreatorUid(headStaffUid);
            data.setStatusName(statusName);
        } else {
            // 修改
            purchaseCode = code;
            data = whPurchaseService.getBeanByCode(purchaseCode);
            if (data == null)
                return R.fail("采购订单获取失败");

            Integer dataStatus = data.getStatus();
            if (!dataStatus.equals(EnumType.Purchase.SAVE.getType()) && !dataStatus.equals(EnumType.Purchase.STEP_1.getType()))
                return R.fail("修改失败订单当前状态：" + EnumType.Purchase.getStatus(dataStatus));
            // 当前修改的商品记录
            List<Long> newPurchaseGoodsIds = goodsJson.stream().map(WhPurchaseGoods::getId)
                    .filter(Objects::nonNull).collect(Collectors.toList());
            // 先删除已有但修改未保存的商品
            whPurchaseGoodsService.dropByCodeAndNotIds(purchaseCode, newPurchaseGoodsIds);

            String statusName = EnumType.Purchase.getStatus(status);
            // 保存新增的商品
            for (WhPurchaseGoods goods : goodsJson) {
                if (goods.getId() == null || goods.getId() <= 0) {
                    goods.setPurchaseCode(purchaseCode);
                    goods.setCreator(headStaffName);
                    goods.setCreatorUid(headStaffUid);
                }
                goods.setStatus(status);
                goods.setStatusName(statusName);
                // 重新计算总数量、总金额
                numCnt += NepUtil.nullToZero(goods.getBuyNum());
                // 总金额
                priceCnt = DoubleUtil.sum(priceCnt, NepUtil.nullToZero(goods.getPrice()));
            }
            whPurchaseGoodsService.saveOrUpdateBatch(goodsJson);
            data.setStatusName(statusName);
        }
        data.setStatus(status);
        data.setBuyNum(numCnt);
        data.setPrice(priceCnt);
        data.setRemark(remark);
        data.setGoodsTypeNum(goodsJson.size());
        data.setExpressInfo(expressInfo);
        data.setExpressPrice(expressPrice);
        whPurchaseService.saveOrUpdate(data);

        // 判断是否都是实体物品
        boolean haveRealStatus = realStatusList.contains(1);
        // 提交采购且是非实体商品，入库记录设置为完成
        if (status == 3 && !haveRealStatus && CollectionUtils.isNotEmpty(goodsJson)) {
            List<WhStockIn> stockInList = new ArrayList<>();
            for (WhPurchaseGoods goods : goodsJson) {
                // 新建已完成的入库记录
                WhStockIn stockIn = PurchaseUtil.newStockInOk(headStaffUid, headStaffName, goods, goods.getBuyNum(), remark, time);
                stockInList.add(stockIn);
            }
            // 更新入库订单状态为已完成
            whPurchaseService.notRealSetOk(purchaseCode, headStaffUid, headStaffName, time);
            // 更新入库的商品状态为已完成
            whPurchaseGoodsService.notRealSetOk(purchaseCode, time);
            // 保存非实体商品的入库记录
            if (CollectionUtils.isNotEmpty(stockInList)) {
                whStockInService.saveOrUpdateBatch(stockInList);

                for (WhStockIn stockIn : stockInList) {
                    // 商品入库，计算入库商品的加权平均价
                    GoodsWetAvgUtil.updateGoodsWetAvgPrice(stockIn.getGoodsName() + "-" + stockIn.getGoodsTypeName(),
                            stockIn.getGoodsId(), stockIn.getGoodsTypeId(), stockIn.getRealNum(), stockIn.getInAmount());
                }
            }
        }

        return R.ok();
    }


    @ApiOperation(value = "添加/修改快递信息")
    @PostMapping(value = "/newExpress", produces = "application/json; charset=UTF-8")
    public R<Object> newExpress(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购订单号") @RequestParam(value = "code") String code,
            @ApiParam(value = "快递信息:[{code:'',name:''}]") @RequestParam(value = "expressJson", required = false) String expressJson,
            @ApiParam(value = "快递金额") @RequestParam(value = "expressPrice", required = false) Double expressPrice
    ) {
        WhPurchase data = whPurchaseService.getByCode(code);
        if (data == null)
            return R.fail("采购订单获取失败");

        String expressInfo = null;
        if (StringUtils.isNotBlank(expressJson)) {
            JSONArray array = JSONArray.parseArray(expressJson);
            if (CollectionUtils.isEmpty(array))
                return R.fail("请填写快递信息");

            expressInfo = OrderFormV3Util.newExpress(array);
            if (StringUtils.isBlank(expressInfo))
                return R.fail("快递信息不完整");
        }

        boolean l = whPurchaseService.updateExpressInfo(code, expressInfo, expressPrice);
        if (!l)
            return R.fail("更新快递信息失败");
        return R.ok();
    }


    @ApiOperation(value = "取消采购订单")
    @PostMapping(value = "/cancel", produces = "application/json; charset=UTF-8")
    public R<Object> cancel(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购订单号") @RequestParam(value = "code") String code,
            @ApiParam(value = "备注") @RequestParam(value = "remark", required = false) String remark
    ) {
        WhPurchase data = whPurchaseService.getByCode(code);
        if (data == null) return R.fail("采购订单获取失败");

        long byPurchaseCodeCnt = whStockInService.getPurchaseCodeCnt(code, null);
        if (byPurchaseCodeCnt > 0) return R.fail("已有入库记录不能取消");

        Date time = DateUtil.getNowDatetime();
        boolean l = whPurchaseService.cancel(code, headStaffUid, headStaffName, remark, time);
        if (!l) return R.fail("取消失败当前状态：" + EnumType.Purchase.getStatus(data.getStatus()));
        whPurchaseGoodsService.cancel(code);
        return R.ok();
    }


    @ApiOperation(value = "验证采购订单")
    @PostMapping(value = "/authPurchase", produces = "application/json; charset=UTF-8")
    public R<Object> authPurchase(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购订单号") @RequestParam(value = "code") String code
    ) {
        WhPurchase data = whPurchaseService.getByCode(code);
        if (data == null) return R.fail("采购订单获取失败");
        if (!data.getStatus().equals(EnumType.Purchase.STEP_2.getType()))
            return R.fail("操作失败订单的状态是：" + EnumType.Purchase.getStatus(data.getStatus()));

        List<WhStockIn> stockInList = whStockInService.getByPurchaseCode(code);
        Map<Long, List<WhStockIn>> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(stockInList)) {
            map = stockInList.stream().collect(Collectors.groupingBy(WhStockIn::getPurchaseGoodsId));
        }
        boolean inNumStatus = false;
        boolean waitInNumStatus = false;
        JSONArray array = new JSONArray();
        List<WhPurchaseGoods> goodsList = whPurchaseGoodsService.getByCode(code);
        for (WhPurchaseGoods goods : goodsList) {
            JSONObject jsonObject = JsonUtil.toJsonObject(goods);
            int inNum = 0;
            int waitInNum = 0;
            int usableNum = 0;
            List<WhStockIn> stockIns = map.get(goods.getId());
            if (CollectionUtils.isNotEmpty(stockIns)) {
                for (WhStockIn stockIn : stockIns) {
                    if (stockIn.getStatus().equals(1)) {
                        inNum += stockIn.getRealNum();
                        usableNum += stockIn.getUsableNum();
                    } else if (stockIn.getStatus().equals(2)) {
                        waitInNum += stockIn.getRealNum();
                    }
                }
            }
            if (inNum == 0) {
                inNumStatus = true;
            }
            if (waitInNum > 0) {
                waitInNumStatus = true;
            }
            jsonObject.put("inNum", inNum);
            jsonObject.put("waitInNum", waitInNum);
            jsonObject.put("usableNum", usableNum);
            array.add(jsonObject);
        }
        if (inNumStatus) {
            return R.fail(4001, "采购的商品还未入库", array);
        }
        if (waitInNumStatus) {
            return R.fail(4001, "有待确认入库的入库记录", array);
        }
        int num = NepUtil.nullToZero(data.getBuyNum());
        int realNum = NepUtil.nullToZero(data.getRealNum());
        if (realNum < num) {
            return R.fail(4001, "实际入库数量小于采购总数", array);
        }

        return R.ok(array);
    }


    @ApiOperation(value = "采购订单设置完成")
    @PostMapping(value = "/setOk", produces = "application/json; charset=UTF-8")
    public R<Object> setOk(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购订单号") @RequestParam(value = "code") String code,
            @ApiParam(value = "采购备注") @RequestParam(value = "remark", required = false) String remark
    ) {
        long enteringCnt = whStockInService.getPurchaseCodeCnt(code, 2);
        if (enteringCnt > 0) return R.fail("采购订单下发现有入库中的入库记录，请先去处理");

        long okCnt = whStockInService.getPurchaseCodeCnt(code, 1);
        long returnCnt = whStockInService.getPurchaseCodeCnt(code, -1);
        if (okCnt <= 0 && returnCnt <= 0) return R.fail("没有已完成或退回的入库记录，不能设置完成");

        Date time = DateUtil.getNowDatetime();
        whPurchaseService.setOk(code, headStaffUid, headStaffName, remark, time);
        whPurchaseGoodsService.setOk(code, time);

        return R.ok();
    }

    @ApiOperation(value = "将21套挑战卡（套）的采购库存 分配给 挑战卡单件采购库存")
    @PostMapping(value = "/modifyPurchase", produces = "application/json; charset=UTF-8")
    public R<Object> modifyPurchase(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "采购订单号") @RequestParam(value = "code") String code,
            @ApiParam(value = "调整数量") @RequestParam(value = "num") Integer num,
            @ApiParam(value = "采购备注") @RequestParam(value = "remark", required = false) String remark
    ) {
        WhPurchase purchase = whPurchaseService.getBeanByCode(code);
        if (null == purchase)
            return R.fail("采购单获取失败");

        List<WhPurchaseGoods> purchaseGoodsList = whPurchaseGoodsService.getBeanByCode(code);
        if (CollectionUtils.isEmpty(purchaseGoodsList))
            return R.fail("采购单的采购商品集合获取失败");
        WhPurchaseGoods purchaseGoods = purchaseGoodsList.get(0);

        List<WhStockIn> stockInList = whStockInService.getByPurchaseCode(code);
        if (CollectionUtils.isEmpty(stockInList))
            return R.fail("采购单的入库记录集合获取失败");
        WhStockIn stockIn = stockInList.get(0);

        GoodsWetPrice goodsWetPrice = goodsWetPriceService.getByGoodsIdAndGoodsTypeId(purchaseGoods.getGoodsId(), purchaseGoods.getGoodsTypeId());
        if (null == goodsWetPrice)
            return R.fail("加权平均价获取失败");

        if (stockIn.getUsableNum() < num)
            return R.fail("剩余库存数量不够调整，剩余库存数量：" + stockIn.getUsableNum());

        if (goodsWetPrice.getUsableNum() < num)
            return R.fail("加权平均价的剩余库存数量不够调整，剩余库存数量：" + goodsWetPrice.getUsableNum());

        // 入库的均价
        double avePrice = stockIn.getUnitPrice();

        // 分配后的数量
        int mdyNum = stockIn.getRealNum() - num;
        // 分配后的总价
        double mdyPrice = DoubleUtil.mul(mdyNum, avePrice);
        // 分配后的剩余库存
        int mdyUsableNum = stockIn.getUsableNum() - num;

        Double wetAvePrice = goodsWetPrice.getWetAvePrice();
        // 调整数量*加权平均价
        double newPrice = DoubleUtil.mul(num, wetAvePrice);
        // 单价金额 = 加权平均价/21
        double singleAvePrice = DoubleUtil.div(wetAvePrice, 21, 4);
        // 单价总金额
        double singlePrice = DoubleUtil.mul(singleAvePrice, num);


        purchase.setBuyNum(mdyNum);
        purchase.setRealNum(mdyNum);
        purchase.setPrice(mdyPrice);
        whPurchaseService.saveOrUpdate(purchase);

        purchaseGoods.setBuyNum(mdyNum);
        purchaseGoods.setRealNum(mdyNum);
        purchaseGoods.setPrice(mdyPrice);
        whPurchaseGoodsService.saveOrUpdate(purchaseGoods);

        stockIn.setBuyNum(mdyNum);
        stockIn.setInAmount(mdyPrice);
        stockIn.setRealNum(mdyNum);
        stockIn.setUsableNum(mdyUsableNum);
        whStockInService.saveOrUpdate(stockIn);

        double mdyUsablePrice = DoubleUtil.mul(mdyUsableNum, goodsWetPrice.getWetAvePrice());
        goodsWetPrice.setUsableNum(mdyUsableNum);
        goodsWetPrice.setUsablePrice(mdyUsablePrice);
        goodsWetPriceService.saveOrUpdate(goodsWetPrice);

        int status = EnumType.Purchase.SAVE.getType();
        String statusName = EnumType.Purchase.SAVE.getName();
        // 新增
        String purchaseCode = KitUtil.getPurchaseCode();
        WhPurchase newPurchase = new WhPurchase();
        newPurchase.setCode(purchaseCode);
        newPurchase.setProjectType(EnumType.BalanceProject.PURCHASE.getType());
        newPurchase.setProjectName(EnumType.BalanceProject.PURCHASE.getName());
        newPurchase.setSupplierId(1L);
        newPurchase.setSupplierName("安徽顺印科技有限公司");
        newPurchase.setCreator("鲍勇志");
        newPurchase.setCreatorId(1L);
        newPurchase.setStatusName(statusName);
        newPurchase.setStatus(status);
        newPurchase.setBuyNum(num);
        newPurchase.setPrice(newPrice);
        newPurchase.setRemark(remark);


        int numCnt = 0;
        Goods goods = goodsService.getById(24L);
        List<GoodsType> goodsTypeList = goodsTypeService.getByGoodsId(24L);
        List<WhPurchaseGoods> newPurchaseGoodList = new ArrayList<>();
        for (GoodsType goodsType : goodsTypeList) {
            WhPurchaseGoods newPurchaseGood = new WhPurchaseGoods();
            newPurchaseGood.setSupplierId(newPurchase.getSupplierId());
            newPurchaseGood.setSupplierName(newPurchase.getSupplierName());
            newPurchaseGood.setGoodsId(goods.getId());
            newPurchaseGood.setGoodsName(goods.getName());
            newPurchaseGood.setGoodsTypeId(goodsType.getId());
            newPurchaseGood.setGoodsTypeName(goodsType.getName());
            newPurchaseGood.setImg(goodsType.getImg());
            newPurchaseGood.setUnit(goodsType.getUnit());
            newPurchaseGood.setRealStatus(1);
            newPurchaseGood.setSupplierPrice(0d);
            newPurchaseGood.setBuyNum(num);
            newPurchaseGood.setUnitPrice(singleAvePrice);
            newPurchaseGood.setPrice(singlePrice);
            newPurchaseGood.setRemark(remark);
            newPurchaseGood.setPurchaseCode(purchaseCode);
            newPurchaseGood.setCreator("鲍勇志");
            newPurchaseGood.setCreatorId(1L);
            newPurchaseGood.setStatus(status);
            newPurchaseGood.setStatusName(statusName);
            newPurchaseGoodList.add(newPurchaseGood);
            numCnt += num;
        }

        newPurchase.setBuyNum(numCnt);
        newPurchase.setGoodsTypeNum(goodsTypeList.size());
        whPurchaseService.saveOrUpdate(newPurchase);
        whPurchaseGoodsService.saveOrUpdateBatch(newPurchaseGoodList);

        return R.ok();
    }

}
